<template>
  <view class="dynamics-container">
    <!-- 页面标题 -->
    <view class="header">
      <view class="title">我的动态</view>
      <view class="subtitle">已发布 {{ dynamics.length }} 条动态</view>
    </view>

    <!-- 动态列表 -->
    <view class="dynamics-list">
      <view class="empty-container" v-if="dynamics.length === 0">
        <image class="empty-image" src="/static/images/empty.png" mode="aspectFit"></image>
        <text class="empty-text">暂无动态，快去发布第一条吧</text>
        <button class="publish-btn" @tap="navigateToPublish">去发布</button>
      </view>

      <view class="dynamic-item" v-for="(dynamic, index) in dynamics" :key="index">
        <!-- 动态头部 -->
        <view class="dynamic-header">
          <image
            class="avatar"
            :src="userInfo.avatar || '/static/images/default-avatar.png'"
            mode="aspectFill"
          ></image>
          <view class="user-info">
            <text class="username">{{ userInfo.username || '未设置昵称' }}</text>
            <text class="post-time">{{ formatDate(dynamic.createTime) }}</text>
          </view>
          <view class="action-buttons">
            <button class="delete-btn" @tap="deleteDynamic(dynamic.id)">删除</button>
            <view class="action-dot" @tap="showActionSheet(dynamic.id)">
              <text class="dot">···</text>
            </view>
          </view>
        </view>

        <!-- 动态内容 -->
        <view class="dynamic-content">
          <text class="content-text">{{ dynamic.content }}</text>

          <!-- 图片展示 -->
          <view class="dynamic-images" v-if="dynamic.images">
            <image
              class="dynamic-image"
              :src="dynamic.images"
              mode="aspectFill"
              @tap="previewImage(dynamic.images)"
            ></image>
          </view>
        </view>

        <!-- 互动数据 -->
        <view class="dynamic-stats">
          <view class="action-item" @tap="likePostAction(dynamic.id)">
            <template v-if="isPostLiked(dynamic.id)">
              <text class="action-icon liked">👍</text>
            </template>
            <template v-else>
              <text class="action-text">点赞</text>
            </template>
            <text class="like-count" v-if="dynamic.like > 0">{{ dynamic.like }}</text>
          </view>
          <view class="action-item" @tap="toggleComments(dynamic.id)">
            <text class="action-icon">💬</text>
            <text class="action-text">评论 {{ dynamic.arrayComment?.length || 0 }}</text>
          </view>
          <view class="action-item" @tap="favoritePostAction(dynamic.id)">
            <text class="action-icon">⭐</text>
            <text class="action-text">收藏</text>
          </view>
        </view>

        <!-- 评论区 -->
        <view class="comments-section" v-if="dynamic.showComments && dynamic.arrayComment?.length">
          <view class="comment-item" v-for="comment in dynamic.arrayComment" :key="comment.id">
            <view class="comment-content-row">
              <text
                class="comment-username"
                @tap="replyToUser(dynamic.id, comment.username, comment.userId)"
                >{{ comment.username }}</text
              ><text class="colon">：</text>
              <text v-if="comment.replyToUsername" class="comment-reply">
                回复
                <text
                  class="reply-name"
                  @tap="replyToUser(dynamic.id, comment.replyToUsername, comment.replyToUserId)"
                  >@{{ comment.replyToUsername }}</text
                >
              </text>
              <text class="comment-text">{{ comment.content }}</text>
            </view>
          </view>
        </view>

        <!-- 评论输入框 -->
        <view class="comment-input-area" v-if="dynamic.showComments">
          <view class="comment-input-row">
            <input
              class="comment-input"
              :placeholder="
                replyInfo[dynamic.id] ? `回复 @${replyInfo[dynamic.id].username}` : '说点什么吧...'
              "
              v-model="commentText[dynamic.id]"
              confirm-type="send"
              @confirm="submitComment(dynamic.id)"
            />
            <view
              v-if="replyInfo[dynamic.id]"
              class="cancel-reply"
              @tap="clearReplyInfo(dynamic.id)"
              >×</view
            >
            <view class="send-btn" @tap="submitComment(dynamic.id)">发送</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部提示 -->
    <view class="list-footer" v-if="dynamics.length > 0 && !hasMore">
      <text class="footer-text">—— 已经到底啦 ——</text>
    </view>

    <!-- 加载中提示 -->
    <view class="loading" v-if="isLoading">
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script>
import { queryMyPosts, deletePost, findLikes, likePost, insertComment } from '@/api/post'

export default {
  data() {
    return {
      dynamics: [], // 动态列表
      userInfo: {}, // 用户信息
      isLoading: false, // 加载状态
      hasMore: true, // 是否有更多数据
      page: 1, // 当前页码
      pageSize: 10, // 每页条数
      replyInfo: {}, // 回复信息
      commentText: {}, // 评论文本
      likedPostIds: [], // 已点赞的帖子ID
    }
  },

  onLoad() {
    this.loadUserInfo()
    this.fetchDynamics()
    this.fetchLikedPosts() // 添加获取点赞状态
  },

  onShow() {
    this.fetchLikedPosts() // 页面显示时更新点赞状态
  },

  onPullDownRefresh() {
    this.page = 1
    this.dynamics = []
    this.hasMore = true
    this.fetchDynamics()
    setTimeout(() => {
      uni.stopPullDownRefresh()
    }, 1000)
  },

  onReachBottom() {
    if (this.hasMore && !this.isLoading) {
      this.page++
      this.fetchDynamics()
    }
  },

  methods: {
    // 加载用户信息
    loadUserInfo() {
      const storedUserInfo = uni.getStorageSync('userInfo')
      if (storedUserInfo) {
        this.userInfo = storedUserInfo
      }
    },

    // 获取动态列表
    fetchDynamics() {
      if (this.isLoading) return

      this.isLoading = true
      uni.showLoading({ title: '加载中...' })

      queryMyPosts()
        .then((res) => {
          console.log('获取我的动态数据:', res)

          if (res.statusCode === 200 && res.data && res.data.code === 200) {
            const newDynamics = res.data.data || []

            // 如果是第一页，则直接替换，否则追加
            if (this.page === 1) {
              this.dynamics = newDynamics

              // 如果数据为空，显示友好提示
              if (newDynamics.length === 0) {
                console.log('暂无动态数据')
              }
            } else {
              this.dynamics = [...this.dynamics, ...newDynamics]
            }

            // 判断是否还有更多数据
            this.hasMore = newDynamics.length === this.pageSize
          } else {
            uni.showToast({
              title: res.data?.info || '获取动态失败',
              icon: 'none',
            })

            // 如果是服务器错误，可以显示示例数据
            if (this.page === 1 && (!res.data || res.data.code !== 200)) {
              this.showExampleData()
            }
          }
        })
        .catch((err) => {
          console.error('获取动态列表失败:', err)
          uni.showToast({
            title: '获取动态失败，请稍后再试',
            icon: 'none',
          })

          // 网络错误时可以显示示例数据
          if (this.page === 1) {
            this.showExampleData()
          }
        })
        .finally(() => {
          this.isLoading = false
          uni.hideLoading()
        })
    },

    // 显示示例数据（当网络错误或服务器错误时）
    showExampleData() {
      console.log('显示示例数据')
      // 这里可以选择是否添加示例数据，或仅保留空状态
      this.dynamics = []
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return ''

      try {
        const date = new Date(dateStr)
        if (isNaN(date.getTime())) return dateStr

        const now = new Date()
        const diff = now - date

        // 24小时内，显示几小时前
        if (diff < 24 * 60 * 60 * 1000) {
          const hours = Math.floor(diff / (60 * 60 * 1000))
          if (hours === 0) {
            const minutes = Math.floor(diff / (60 * 1000))
            return minutes <= 0 ? '刚刚' : `${minutes}分钟前`
          }
          return `${hours}小时前`
        }

        // 一周内，显示周几
        if (diff < 7 * 24 * 60 * 60 * 1000) {
          const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
          return days[date.getDay()]
        }

        // 超过一周，显示具体日期
        return `${date.getMonth() + 1}月${date.getDate()}日`
      } catch (e) {
        console.error('日期格式化错误:', e)
        return dateStr
      }
    },

    // 预览图片
    previewImage(url) {
      if (!url) return
      uni.previewImage({
        urls: [url],
        current: url,
      })
    },

    // 显示操作菜单
    showActionSheet(id) {
      uni.showActionSheet({
        itemList: ['编辑', '删除'],
        success: (res) => {
          if (res.tapIndex === 0) {
            // 编辑动态
            this.editDynamic(id)
          } else if (res.tapIndex === 1) {
            // 删除动态
            this.deleteDynamic(id)
          }
        },
      })
    },

    // 编辑动态
    editDynamic(id) {
      const dynamic = this.dynamics.find((item) => item.id === id)
      if (!dynamic) return

      uni.navigateTo({
        url: `/pages/publish/publish?id=${id}&content=${encodeURIComponent(
          dynamic.content,
        )}&image=${encodeURIComponent(dynamic.images || '')}`,
      })
    },

    // 删除动态
    deleteDynamic(id) {
      uni.showModal({
        title: '删除动态',
        content: '确定要删除这条动态吗？删除后将无法恢复',
        confirmColor: '#ff6b6b',
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({ title: '删除中...' })

            deletePost(id)
              .then((res) => {
                console.log('删除动态响应:', res)

                // 检查响应状态
                if (res.statusCode === 200 && res.data) {
                  const result = res.data

                  // 检查业务状态码
                  if (result.code === 200) {
                    // 删除成功，从列表中移除该动态
                    this.dynamics = this.dynamics.filter((item) => item.id !== id)

                    uni.showToast({
                      title: '删除成功',
                      icon: 'success',
                    })

                    // 更新动态数量显示
                    if (this.dynamics.length === 0 && this.page > 1) {
                      // 如果当前页已无数据且不是第一页，回到上一页
                      this.page--
                      this.fetchDynamics()
                    }
                  } else {
                    uni.showToast({
                      title: result.info || '删除失败',
                      icon: 'none',
                    })
                  }
                } else {
                  uni.showToast({
                    title: '删除失败，请稍后再试',
                    icon: 'none',
                  })
                }
              })
              .catch((err) => {
                console.error('删除动态失败:', err)
                uni.showToast({
                  title: '删除失败，请稍后再试',
                  icon: 'none',
                })
              })
              .finally(() => {
                uni.hideLoading()
              })
          }
        },
      })
    },

    // 跳转到发布页面
    navigateToPublish() {
      uni.navigateTo({
        url: '/pages/publish/publish',
      })
    },

    // 获取点赞状态
    fetchLikedPosts() {
      findLikes()
        .then((res) => {
          console.log('获取点赞数据响应:', res)

          if (res.statusCode === 200 && res.data) {
            const result = res.data
            if (result.code === 200 && Array.isArray(result.data)) {
              // 清空之前的点赞ID列表
              this.likedPostIds = []

              // 提取已点赞的帖子ID
              result.data.forEach((like) => {
                if (like.isLike === '是') {
                  // 确保将postId转换为数字类型
                  const postId = Number(like.postId)
                  if (!isNaN(postId) && !this.likedPostIds.includes(postId)) {
                    this.likedPostIds.push(postId)
                  }
                }
              })

              console.log('已点赞的帖子ID列表:', this.likedPostIds)

              // 更新帖子列表中的点赞状态
              this.updatePostsLikeStatus()
            } else {
              console.warn('获取点赞数据异常:', result)
            }
          }
        })
        .catch((err) => {
          console.error('获取点赞数据失败:', err)
        })
    },

    // 更新帖子的点赞状态
    updatePostsLikeStatus() {
      if (this.dynamics.length === 0) return

      // 遍历帖子，标记已点赞状态
      this.dynamics = this.dynamics.map((post) => {
        return {
          ...post,
          isLiked: this.likedPostIds.includes(post.id),
        }
      })
    },

    // 判断帖子是否已点赞
    isPostLiked(postId) {
      console.log(`检查帖子ID ${postId} 是否点赞, likedPostIds:`, this.likedPostIds)
      // 确保进行数字类型比较
      return this.likedPostIds.includes(Number(postId))
    },

    // 点赞动态
    likePostAction(postId) {
      // 转换为数字类型确保一致性
      postId = Number(postId)

      // 检查当前点赞状态
      const isCurrentlyLiked = this.isPostLiked(postId)
      console.log(`点赞操作: postId=${postId}, 当前状态=${isCurrentlyLiked ? '已点赞' : '未点赞'}`)

      likePost(postId)
        .then((res) => {
          console.log('点赞操作响应:', res)
          if (res.statusCode === 200 && res.data) {
            const result = res.data
            if (result.code === 200) {
              // 更新本地点赞状态
              const postIndex = this.dynamics.findIndex((p) => p.id === postId)

              if (postIndex !== -1) {
                // 更新点赞数
                if (!isCurrentlyLiked) {
                  // 点赞数+1
                  this.$set(
                    this.dynamics[postIndex],
                    'like',
                    (this.dynamics[postIndex].like || 0) + 1,
                  )

                  // 添加到已点赞列表
                  if (!this.likedPostIds.includes(postId)) {
                    this.likedPostIds.push(postId)
                  }

                  uni.showToast({
                    title: '点赞成功',
                    icon: 'success',
                  })
                } else {
                  // 点赞数-1，但不低于0
                  const currentLikes = this.dynamics[postIndex].like || 0
                  this.$set(this.dynamics[postIndex], 'like', Math.max(0, currentLikes - 1))

                  // 从已点赞列表移除
                  const index = this.likedPostIds.indexOf(postId)
                  if (index !== -1) {
                    this.likedPostIds.splice(index, 1)
                  }

                  uni.showToast({
                    title: '取消点赞',
                    icon: 'success',
                  })
                }

                // 更新列表状态
                this.updatePostsLikeStatus()
              }
            } else {
              uni.showToast({
                title: result.info || '操作失败',
                icon: 'none',
              })
            }
          } else {
            uni.showToast({
              title: '网络错误',
              icon: 'none',
            })
          }
        })
        .catch((err) => {
          console.error('点赞操作失败:', err)
          uni.showToast({
            title: '操作失败，请稍后再试',
            icon: 'none',
          })
        })
    },

    // 切换评论区显示/隐藏
    toggleComments(postId) {
      this.dynamics = this.dynamics.map((post) => {
        if (post.id === postId) {
          return {
            ...post,
            showComments: !post.showComments,
          }
        }
        return post
      })
    },

    // 设置回复目标
    replyToUser(postId, username, userId) {
      this.$set(this.replyInfo, postId, {
        userId,
        username,
      })

      // 聚焦到输入框 - 改用uni-app的方式
      setTimeout(() => {
        // 将目标和提示消息显示出来即可，不需要强制聚焦
        uni.showToast({
          title: `回复 @${username}`,
          icon: 'none',
          duration: 1000,
        })
      }, 100)
    },

    // 清除回复信息
    clearReplyInfo(postId) {
      try {
        // 第一种方法：使用ES6 spread语法创建新对象
        const newReplyInfo = { ...this.replyInfo }
        delete newReplyInfo[postId]
        this.replyInfo = newReplyInfo

        // 如果上面的方法失败，可以使用下面的替代方案
        // this.replyInfo[postId] = undefined;
      } catch (error) {
        console.error('清除回复信息失败:', error)
        // 直接将对应项设为undefined
        this.replyInfo[postId] = undefined
      }
    },

    // 提交评论
    submitComment(postId) {
      const comment = this.commentText[postId]
      if (!comment || comment.trim() === '') {
        uni.showToast({
          title: '评论内容不能为空',
          icon: 'none',
        })
        return
      }

      // 获取回复信息
      const replyTo = this.replyInfo[postId]

      // 使用API发送评论
      const commentData = {
        postId: postId,
        content: comment,
        replyToUserId: replyTo ? replyTo.userId : null,
        replyToUsername: replyTo ? replyTo.username : null,
      }

      // 先清空评论文本和回复信息，提升用户体验
      const commentContent = this.commentText[postId]
      this.$set(this.commentText, postId, '')
      this.clearReplyInfo(postId)

      uni.showLoading({
        title: '提交中...',
      })

      insertComment(commentData)
        .then((res) => {
          uni.hideLoading()
          console.log('评论提交响应:', res)
          const response = res.data

          if (response && response.code === 200) {
            uni.showToast({
              title: '评论成功',
              icon: 'success',
              duration: 1500,
            })

            // 短暂延迟后刷新数据，确保服务器已处理完成
            setTimeout(() => {
              this.fetchDynamics()
            }, 300)
          } else {
            // 恢复之前的评论内容，允许用户重试
            this.$set(this.commentText, postId, commentContent)
            if (replyTo) {
              this.$set(this.replyInfo, postId, replyTo)
            }

            uni.showToast({
              title: response?.info || '评论失败',
              icon: 'none',
            })
          }
        })
        .catch((err) => {
          uni.hideLoading()
          console.error('评论提交错误:', err)

          // 恢复之前的评论内容，允许用户重试
          this.$set(this.commentText, postId, commentContent)
          if (replyTo) {
            this.$set(this.replyInfo, postId, replyTo)
          }

          uni.showToast({
            title: '评论失败，请稍后再试',
            icon: 'none',
          })
        })
    },

    // 收藏动态
    favoritePostAction(postId) {
      uni.showToast({
        title: '收藏成功',
        icon: 'success',
      })
    },
  },
}
</script>

<style lang="scss">
@import '@/styles/variables.scss';

.dynamics-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 40rpx;

  .header {
    height: 180rpx;
    background: linear-gradient(180deg, $theme-color 0%, $light-theme-color 100%);
    border-radius: 0 0 40rpx 40rpx;
    padding: 40rpx 40rpx 30rpx;
    color: #fff;

    .title {
      font-size: 36rpx;
      font-weight: bold;
    }

    .subtitle {
      font-size: 24rpx;
      margin-top: 10rpx;
      opacity: 0.8;
    }
  }

  .dynamics-list {
    padding: 20rpx 30rpx;
    margin-top: -40rpx;

    .dynamic-item {
      background-color: #fff;
      border-radius: 16rpx;
      margin-bottom: 30rpx;
      padding: 30rpx;
      box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);

      .dynamic-header {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;
        position: relative;

        .avatar {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
          background-color: #eee;
        }

        .user-info {
          margin-left: 20rpx;
          flex: 1;

          .username {
            font-size: 28rpx;
            font-weight: 500;
            color: #333;
          }

          .post-time {
            font-size: 24rpx;
            color: #999;
            margin-top: 6rpx;
            display: block;
          }
        }

        .action-buttons {
          display: flex;
          align-items: center;

          .delete-btn {
            background-color: #ff6b6b;
            color: #fff;
            font-size: 24rpx;
            padding: 4rpx 20rpx;
            height: 50rpx;
            line-height: 42rpx;
            text-align: center;
            border-radius: 25rpx;
            margin-right: 10rpx;
            border: none;
            box-shadow: 0 4rpx 8rpx rgba(255, 107, 107, 0.2);

            &::after {
              border: none;
            }
          }

          .action-dot {
            width: 60rpx;
            height: 60rpx;
            display: flex;
            align-items: center;
            justify-content: center;

            .dot {
              font-size: 40rpx;
              font-weight: bold;
              color: #999;
              transform: rotate(90deg);
            }
          }
        }
      }

      .dynamic-content {
        margin-bottom: 20rpx;

        .content-text {
          font-size: 28rpx;
          color: #333;
          line-height: 1.6;
        }

        .dynamic-images {
          margin-top: 20rpx;

          .dynamic-image {
            width: 100%;
            height: 350rpx;
            border-radius: 12rpx;
            background-color: #f5f5f5;
          }
        }
      }

      .dynamic-stats {
        display: flex;
        padding: 16rpx 0;
        border-top: 1px solid #f5f5f5;

        .action-item {
          display: flex;
          align-items: center;
          margin-right: 20rpx;
          padding: 6rpx 10rpx;
          border-radius: 6rpx;
          min-width: 80rpx;
          justify-content: center;
        }

        .action-icon {
          font-size: 36rpx;
          transition: all 0.3s ease;
        }

        .action-text {
          font-size: 28rpx;
          color: #666;
        }

        .liked {
          color: #ff4757;
          font-size: 40rpx;
          transform: scale(1.2);
          transition: all 0.3s ease;
          text-shadow: 0 2rpx 4rpx rgba(255, 71, 87, 0.3);
        }

        .like-count {
          font-size: 24rpx;
          color: #999;
          margin-left: 4rpx;
          min-width: 24rpx;
          text-align: center;
        }

        .liked + .like-count {
          color: #ff4757;
          font-weight: bold;
        }
      }
    }
  }

  .empty-container {
    padding: 60rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .empty-image {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 30rpx;
    }

    .empty-text {
      font-size: 28rpx;
      color: #999;
      margin-bottom: 40rpx;
    }

    .publish-btn {
      background-color: $theme-color;
      color: #fff;
      width: 300rpx;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      border-radius: 40rpx;
      font-size: 28rpx;
      box-shadow: 0 6rpx 12rpx rgba(147, 112, 219, 0.2);
    }
  }

  .list-footer {
    text-align: center;
    padding: 30rpx 0;

    .footer-text {
      font-size: 24rpx;
      color: #999;
    }
  }

  .loading {
    text-align: center;
    padding: 20rpx 0;

    .loading-text {
      font-size: 24rpx;
      color: #999;
    }
  }

  .comments-section {
    margin-top: 20rpx;
    background-color: #f9f9f9;
    border-radius: 16rpx;
    padding: 20rpx;

    .comment-item {
      padding: 16rpx 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .comment-content-row {
        display: flex;
        flex-wrap: wrap;
        align-items: center;

        .comment-username {
          font-size: 26rpx;
          font-weight: 500;
          color: #fff;
          background-color: $theme-color;
          padding: 4rpx 12rpx;
          border-radius: 24rpx;

          /* 添加点击效果 */
          &:active {
            opacity: 0.7;
          }
        }

        .colon {
          font-size: 26rpx;
          color: #333;
          margin: 0 4rpx;
        }

        .comment-reply {
          font-size: 24rpx;
          color: #666;
          margin-right: 8rpx;

          .reply-name {
            color: $theme-color;

            /* 添加点击效果 */
            &:active {
              opacity: 0.7;
            }
          }
        }

        .comment-text {
          font-size: 26rpx;
          color: #333;
          line-height: 1.5;
          flex: 1;
        }
      }
    }
  }

  .comment-input-area {
    display: flex;
    margin-top: 20rpx;

    .comment-input-row {
      display: flex;
      align-items: center;
      width: 100%;
    }

    .comment-input {
      flex: 1;
      height: 70rpx;
      background-color: #f5f5f5;
      border-radius: 35rpx;
      padding: 0 30rpx;
      font-size: 26rpx;
    }

    .cancel-reply {
      font-size: 32rpx;
      color: #999;
      padding: 0 10rpx;
      margin: 0 5rpx;
      &:active {
        opacity: 0.7;
      }
    }

    .send-btn {
      width: 110rpx;
      height: 70rpx;
      background-color: $theme-color;
      color: #fff;
      border-radius: 35rpx;
      font-size: 26rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 10rpx;
    }
  }
}
</style>
